<?php
session_start();
// Connect to the DB.
$_SESSION["errmsg"] = '';
require_once '../include/config.lib.php';
require_once '../include/database.lib.php';

$paperId = $_SESSION["bibtexid"];

$url = "../paper_view.php?id=". $paperId  ."#tabs-2";

function buildRedirectPath($redirectTo) {
	return "<HTML><META http-equiv=\"refresh\" content=\"0; url='".$redirectTo."'\"></HTML>";
}

if(isset($_POST['submitEdit'])){
if(isset($_SESSION["accountNo"])){//user has logged in

	ConnectToDB();
	
	/*$selectid = DBExecute("SELECT id FROM person WHERE username = '".$_SESSION["accountNo"]."'");
	$id = $selectid->fetchAssocRow();//find the person's id
	$personid = $id['ID'];*/

	$authorsReq = DBExecute(" SELECT authors FROM bibtex
						WHERE id = ? ", array($paperId));	//find the authors
	
	if(0){//this part is not needed right now, maybe useful latter, 
		$_SESSION["errmsg"] = '';
		echo "<HTML><META http-equiv=\"refresh\" content=\"0; url='".$url."'\"></HTML>";//redirect to the paper's page
	}
	
	else {
		//Perform validation on the fields. Redirect back to teh paperpage if incorrect format is submitted
		if (isset($_POST["title"]) && strlen($_POST["title"]) < 4 && !preg_match("/^[a-zA-Z0-9\,\;\.\s]*$/", $_POST["title"])){ //entry must be more than 3 chars long
			$_SESSION["errmsg"] = 'Title should be string with at least 4 characters!';
			echo buildRedirectPath($url);
		}
		else if (isset($_POST["title"])){ 
			$newTitle = $_POST["title"];
		}
		
		if(isset($_POST["authors"]) && strlen($_POST["authors"]) < 3 ){ //entry must be more than 2 chars long
			echo buildRedirectPath($url);
		}
		else if (isset($_POST['authors'])){ 
			$newAuthors = $_POST['authors'];
			$authorNames = explode(';', $newAuthors);		//separate authors via delimiting semicolon
			
			for($i = 0; $i< count($authorNames); $i++){	    //trim spaces from names
				$authorNames[$i] = trim($authorNames[$i]);
				
				if(!preg_match("/^[a-zA-Z0-9\,\;\.\s]*$/", $authorNames[$i])){
					$_SESSION["errmsg"] = 'Author names must contain at least 3 characters!';
					echo buildRedirectPath($url);
				}
			}
		}
		
		if(isset($_POST['doi']) && !preg_match("/^[0-9]*$/", $_POST["doi"])){	//must be numerical
			$_SESSION["errmsg"] = 'DOI must be numerical!';
			echo buildRedirectPath($url);
		}
		else if (isset($_POST['doi'])){ 
			$newDoi = $_POST['doi'];
		}
		
		if(isset($_POST['isbn']) && !preg_match("/^[a-zA-Z0-9\,\;\.\s]*$/", $_POST["isbn"])){ //must be numerical
			$_SESSION["errmsg"] = 'ISBN must be numerical!';
			echo buildRedirectPath($url);
		}
		else if (isset($_POST['isbn'])){ 
			$newIsbn = $_POST['isbn'];
		}

		if($_POST['title'] != null){
			$change = DBExecute("UPDATE bibtex SET title =? WHERE id =?", array(htmlentities($newTitle),$paperId));
		}
	
		if($_POST['authors'] != null){

			//update the 'authors field' of the bibtex entry:
			DBExecute('UPDATE bibtex SET authors = ?  			
				WHERE id = ?', array($_POST['authors'],$paperId));
			
			/*$resourceIDs = DBExecute(' SELECT r.id AS resourceID FROM resource r
				WHERE r.bibtexid = ?', array($paperId)); //resource ids from this paper
			
			//remove the authoring entries currently associated with this paper. Then we will re-add them
			while ( $removeIDs = $resourceIDs->fetchAssocRow()) {
				$removeAuthors = DBExecute("DELETE FROM authoring WHERE resourceid = ? 
											AND personid NOT IN (SELECT p.id from person p where p.username IS NOT NULL) ", array($removeIDs['RESOURCEID']));
			}			

			//check if the authors are already in the DB, and add entries in the authoring table for the authors already in existance	
			for($i = 0; $i< sizeof($authorNames); $i++){
				//check if author name is already in DB
				$authorCheck1 = DBExecute("SELECT COUNT(*) as matches FROM person p WHERE lower(p.name) = ? AND p.username IS null", array(strtolower($authorNames[$i])));
				$num = $authorCheck1->fetchAssocRow();
				
				$resourceIDs = DBExecute(' SELECT r.id AS resourceID FROM resource r
					WHERE r.bibtexid = ?', array($paperId)); //resource ids from this paper				
				
				if($num['MATCHES'] > 0){	//if the author already exists in the DB, so just add them to the autoring table
					//retrieve the ID of the author so we can add it to the authoring table
					$authorIDreq = DBExecute("SELECT id FROM person p WHERE lower(p.name) = ? AND p.username IS null", array(strtolower($authorNames[$i])));
					$authorID = $authorIDreq->fetchAssocRow();
			
					while ( $row = $resourceIDs->fetchAssocRow()) {	//add autoring entries for each resource associated with the paper
						$resourceID = $row['RESOURCEID'];
						$newAuthor = DBExecute("INSERT INTO authoring (personid,resourceid) VALUES (?, ?)", array($authorID['ID'], $resourceID));
					}
				}

				else{	//if the author doesnt yet exist in the DB, then add them to the Authoring table and Person table
					//insert the new person into the person table
					$newPerson = DBExecute("INSERT INTO person (name) VALUES (?)", array($authorNames[$i]));
					
					//retrieve the ID of the new person
					$authorIDreq = DBExecute("SELECT id FROM person p WHERE lower(p.name) = ?", array(strtolower($authorNames[$i])));
					$authorID = $authorIDreq->fetchAssocRow();
					
					//insert the new person into the authoring table
					while ( $row = $resourceIDs->fetchAssocRow()) {	//add autoring entries for each resource associated with the paper
						$resourceID = $row['RESOURCEID'];
						$newAuthor = DBExecute("INSERT INTO authoring (personid,resourceid) VALUES (?, ?)", array($authorID['ID'], $resourceID));
					}
				}*/
			}
		}
	
		if($_POST['doi'] != null){			
			$change = DBExecute("UPDATE bibtex SET doi =? WHERE id =?", array($newDoi,$paperId));
		}
		
		if($_POST['isbn'] != null){			
			$change2 = DBExecute("UPDATE bibtex SET isbn =? WHERE id =?", array($newIsbn,$paperId));
		}

		echo buildRedirectPath($url);//redirect to the paper's page
	}

else{//user hasn't logged in
	$_SESSION["errmsg"] = "You didn't log in.";	
	echo "<HTML><META http-equiv=\"refresh\" content=\"0; url=../login.php\"></HTML>";//redirect to the login page
}
}
else{
	echo buildRedirectPath($url);
}
?>